package examples

import org.offsync.nio.IoService
import org.offsync.nio.ServerSocketChannel
import org.offsync.rich._
import org.offsync.util.Window

object EchoServer {
  def main(args: Array[String]): Unit = {
    if (args.length != 2) {
      System.err.println("Usage: server <port> <runtime>")
      exit(1)
    }
    
    val port = args(0).toInt
    val runtime = args(1).toInt
    
    new IoService().using { ioService =>
      ServerSocketChannel.open("localhost", port).using { serverChannel =>
        serverChannel.accept(ioService) { getSocket =>
          try {
            val sessionChannel = getSocket()
            val window = Window to (new Array[Byte](100))
            def performSessionRead(): Unit = {
              sessionChannel.read(ioService, window) { getBytesRead =>
                try {
                  val bytesRead = getBytesRead()
                  if (bytesRead < 0) {
                  } else {
                    val dataWindow = window.until(bytesRead)
                    val dataString = dataWindow.asString
                    sessionChannel.write(ioService, window.until(bytesRead)) { getBytesWritten =>
                      try {
                        val bytesWritten = getBytesWritten()
                        performSessionRead()
                      } catch {
                        case e => System.err.println("exception: " + e)
                      }
                    }
                  }
                } catch {
                  case e => System.err.println("exception: " + e)
                }
              }
            }
            performSessionRead()
          } catch {
            case e => System.err.println("exception: " + e)
          }
        }
        println("runtime: " + runtime)
        runtime.seconds.sleep()
      }
    }
  }
}
